import {Component, OnInit} from '@angular/core';
import {CommonPage} from '../common-page';
import {environment} from '../../../../environments/environment';
import {CookieHelper} from '../../../shared/utils';
import {CacheKey, CookieKey} from '../../../shared/components/dhlcomponent/enums';
import {ObjectUtil} from '../../../shared/utils/object-util';
import * as moment from 'moment';

@Component({
  styleUrls: ['login.less'],
  templateUrl: './login.component.html'
})
export class LoginComponent extends CommonPage implements OnInit {


  userName;
  password;
  appName;
  btnLoading = false;
  showTip = false;
  tipBrowserClass;
  year;

  ngOnInit(): void {
    this.appName = environment.appName;
    this.getBrowser();

    this.year = moment().year();
    const uuid = CookieHelper.get(CookieKey.USER_ID);
    const routeUrl = CookieHelper.get(CookieKey.DEFAULT_ROUTE);
    const params = CookieHelper.get(CookieKey.DEFAULT_ROUTE_PARAMS);
    const urlParams = params ? JSON.parse(CookieHelper.get(CookieKey.DEFAULT_ROUTE_PARAMS)) : {};
    const loginData = this.cacheService.getItem(CacheKey.LOGIN_ACCOUNT_DATA);
    if (ObjectUtil.isHaveValue(uuid)) {
      if (ObjectUtil.isHaveValue(loginData)) {
        this.successLogin(loginData, routeUrl, urlParams);
      } else {
        this.requestService.get('login/acctdata').subscribe((data) => {
          if (data) {
            this.successLogin(data, routeUrl, urlParams);
          }
        });
      }
    } else {
      this.cacheService.clear();
    }

  }

  keyDown({code}) {
    if (code == 'Enter') {
      this.onSubmit();
    }
  }

  successLogin(loginAcctData, routeUrl, urlParams) {
    this.cacheService.setItem(CacheKey.LOGIN_ACCOUNT_DATA, loginAcctData);
    const {menus = {}, projects = [], manageProjects = [], loginUser} = loginAcctData;
    if (projects.length > 0) {
      const pcode = projects[0].code;
      const menu = menus[pcode] && menus[pcode][0] ? menus[pcode][0].menu : {};
      this.cacheService.setItem(CacheKey.ACTIVE_MENU, menu);
    }
    this.cacheService.setItem(CacheKey.MENUS, menus);
    this.cacheService.setItem(CacheKey.PROJECTS, projects);
    this.cacheService.setItem(CacheKey.MANAGE_PROJECTS, manageProjects);
    this.cacheService.setItem(CacheKey.LOGIN_USER, loginUser);
    const preUrl = CookieHelper.get(CookieKey.REQUEST_PAGE);
    if (preUrl) {
      this.router.navigateByUrl(preUrl);
    } else {
      this.router.navigate([`/${this.appCode}/${routeUrl}`], {queryParams: urlParams});
    }
  }

  onSubmit(): void {
    if (this.userName) {
      if (this.getBrowser()) {
        this.btnLoading = true;
        this.requestService.get(`login/login`,
          {
            password: this.password,
            userName: this.userName
          })
          .subscribe(data => {
            if (data) {
              this.afterLoginSuccess(data);
            } else {
              this.btnLoading = false;
            }
          });
      }
    }
  }


  afterLoginSuccess({token, uuid, roles, routeUrl, urlParams}): void {

    if (token == undefined || token == '') {
      this.btnLoading = false;
      return;
    }

    this.setTokenCookie(token, environment.tokenExpireTime);
    CookieHelper.set(CookieKey.USER_ID, uuid);
    CookieHelper.set(CookieKey.DEFAULT_ROUTE, routeUrl);
    CookieHelper.set(CookieKey.DEFAULT_ROUTE_PARAMS, urlParams);
    this.requestService.get(`/${this.appCode}/login/acctdata`).subscribe((data) => {
      this.btnLoading = false;
      if (data) {
        this.successLogin(data, routeUrl, urlParams);
      }
    });
  }


  setTokenCookie(token: string, expiresInHours: number): void {
    const expiresDate = new Date(new Date().getTime() + expiresInHours * 3600000);
    CookieHelper.set(environment.tokenCookieKey, token, {expires: expiresDate});
  }


  getBrowser() {
    const ua = navigator.userAgent.toLowerCase();
    this.showTip = false;
    this.tipBrowserClass = '';
    if (!(ua.match(/firefox\/([\d.]+)/) || ua.match(/chrome\/([\d.]+)/) || ua.match(/edge\/([\d.]+)/))) {
      this.showTip = true;
      this.tipBrowserClass = 'tipBrowser';
      setTimeout(() => {
        this.tipBrowserClass = '';
      }, 3000);
      return false;
    }
    return true;
  }

}








